//
//  UnitProxy.m
//  SpaceStorm
//
//  Created by 祥 雍 on 13-6-8.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//
//
//  用户代理，数据中心，单件类

#import "UnitProxy.h"
#import "cocos2d.h"

@implementation UnitProxy

@synthesize userData = _userData;
@synthesize selectUserDataKey = _selectUserDataKey;

static UnitProxy *sharedDataManager = nil;

+ (UnitProxy *) sharedManager
{
    @synchronized(self)
    {
        if (sharedDataManager == nil)
        {
            [[self alloc] init];
        }
    }
    
    return sharedDataManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if(sharedDataManager == nil)
        {
            sharedDataManager = [super allocWithZone:zone];
            return sharedDataManager;
        }
    }
    
    return nil;
}

-(id) init
{
	if( (self=[super init])) 
    {
        ud = [NSUserDefaults standardUserDefaults];  
    }
    
	return self;
}

/**
	保存用户数据
 */
-(void) saveUserData
{
    if(self.userData != nil && _selectUserDataKey != nil)
    {
        NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:self.userData];  
        [ud setObject:udObject forKey:self.selectUserDataKey]; 
        CCLOG(@"用户数据保存成功");
    }
}

/**
	根据存档的key,载入用户数据
	@param userDataKey 存档的key,Variable里面定义
 */
-(void) loadUserDataByKey:(NSString*)userDataKey
{
    NSData* udObject = [ud objectForKey:userDataKey];  
    self.userData = [NSKeyedUnarchiver unarchiveObjectWithData:udObject];  
    CCLOG(@"用户数据载入成功");
}

/**
	创建默认的用户数据
	@param userDataKey 存档的key,Variable里面定义
 */
-(void) createUserDataByKey:(NSString*)userDataKey
{
    //创建新用户数据
    UserData* userData = [[UserData alloc] init];
    self.userData = userData;
    [userData release];
    userData = nil;
    CCLOG(@"创建默认用户数据成功");
    
    //根据key值存档
    self.selectUserDataKey = userDataKey;
    [self saveUserData];
}

-(void) dealloc
{
    if (_userData) 
    {
        [_userData release];
        _userData = nil;
    }
    
    if (_selectUserDataKey) 
    {
        [_selectUserDataKey release];
        _selectUserDataKey = nil;
    }
    
    // 不要忘记调用"super dealloc" 
    [super dealloc];
}

@end
